﻿<%@ WebHandler Language="C#" Class="viewHouse" %>

using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using Chenxin.Lib.Utility;
using System.Data;
using System.Collections;

public class viewHouse : AjaxHandlerBase
{
    public viewHouse()
    {
        //添加带看(缓存中数据)
        htTypePermit.Add("addcache", Constants.Permit_ViewHouseAdd);
        htTypePermit.Add("edit", Constants.Permit_EditViewHouse);
        htTypePermit.Add("view", Constants.Permit_ViewHouse_Detail);
    }
    
    override public void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";

        string strOp = context.Request.Params["op"];
        string strResponse = "";
        switch (strOp.ToLower())
        {
            case "addcache":
                strResponse = AddViewHouse(context);
                break;
            case "delcache":
                strResponse = DelCacheViewHouse(context);
                break;
            case "deldb":
                strResponse = DelDbViewHouse(context);
                break;
            case "add":
                strResponse = SaveViewHouse(context);
                break;
            case "edit":
                strResponse = EditViewHouse(context);
                break;
            case "search":
                strResponse = SearchViewHouse(context);
                break;
            case "getlist":
                strResponse = GetCacheViewHouseList(context);
                break;
            case "getmodel":
                strResponse = GetViewHouseModel(context);
                break;
            case "getcustomertracelist":
                strResponse = GeCustomerTraceList(context);
                break;
            case "getmodelid":
                strResponse = GetViewHouseId(context);//根据客户ID获取带看单ID 
                break;
            default:
                break;
        }
        context.Response.Write(strResponse);
    }

    /// <summary>
    /// 根据参数中的房源ID查询房源跟单数据;
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
    private string GeCustomerTraceList(HttpContext context)
    {
        try
        {
            Guid houseId = (string.IsNullOrEmpty(context.Request["customerid"])) ? Guid.Empty : new Guid(context.Request["customerid"]);
            if (houseId == Guid.Empty)
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "参数错误，房源标识丢失");
            }

            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
            string fieldlist = "*";
            string fieldtablelist = "*";
            string orderfield = "House_TraceInfo.TraceTime desc";
            string strwhere = string.Format("(houseId='{0}' AND IsHide = 0 AND Status = 1)", houseId);

            System.Data.DataSet dshousetracelist = null;
            if (iPageIndex == 1)
            {
                //分页第一页从缓存中读取
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
                string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_TRACE + "." + "10", houseId);

                dshousetracelist = cs.GetDataSet(strCachKey);
                if (!cs.Hit)
                {
                    //若未命中。从查询数据库中读取
                    dshousetracelist = Chenxin.Lib.House.DAL.House_TraceInfo.GetList(
                        iPageIndex, iPageSize, orderfield, "House_TraceInfo", strwhere, fieldlist, fieldtablelist, true);

                    cs.Set(strCachKey, dshousetracelist, DateTime.Now.AddMinutes(5));
                }
            }
            else
            {
                dshousetracelist = Chenxin.Lib.House.DAL.House_TraceInfo.GetList(
                iPageIndex, iPageSize, orderfield, "House_TraceInfo", strwhere, fieldlist, fieldtablelist, true);
            }

            int count = (int)dshousetracelist.Tables[1].Rows[0][0];

            string strHtml = "";
            if (!GetHouseTraceListHtml(dshousetracelist, out strHtml))
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误");
            }

            dshousetracelist.Dispose();
            dshousetracelist = null;
            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);

        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" + ex.Message);
        }
    }

    /// <summary>
    /// 生成房源跟单列表
    /// </summary>
    /// <param name="dslist"></param>
    /// <param name="strHtml"></param>
    /// <returns></returns>
    private bool GetHouseTraceListHtml(System.Data.DataSet dslist, out string strHtml)
    {


        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append("<table width=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
        sb.Append("<thead>");
        sb.Append("<tr>");
        sb.Append("<th width=\"50%\" style=\"text-align:left;\">跟单内容</th>");
        sb.Append("<th width=\"20%\" style=\"text-align:left;\">跟单人/部门</th>");
        sb.Append("<th width=\"30%\" style=\"text-align:left;\">跟单时间</th>");
        sb.Append("</tr>");
        sb.Append("</thead>");
        sb.Append("<tbody>");
        foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
        {
            sb.AppendFormat("<tr>");
            sb.AppendFormat("<td>{0}</td>",DatasetHelper.GetValue(row, "TraceContext", ""));
            sb.AppendFormat("<td>{0}</td>",DatasetHelper.GetValue(row, "Tractor", "-") + "/" + DatasetHelper.GetValue(row, "Depart", "-"));
            sb.AppendFormat("<td>{0}</td>",DatasetHelper.GetValue(row, "TraceTime", ""));
            sb.AppendFormat("</tr>");
        }
        if (dslist.Tables[0].Rows.Count==0)
        {
            sb.AppendFormat("<tr>");
            sb.AppendFormat("<td colspan=\"3\" style=\"text-align:center\">{0}</td>","没有跟单内容!");
            sb.AppendFormat("</tr>");
        }
        sb.Append("</tbody></table>");
        //sb.Append("</div>");

        strHtml = sb.ToString();
        return true;
    }
    
    private string AddViewHouse(HttpContext context)
    {
        try
        {
            //转换成实体
            string strHouseId = context.Request.Params["houseid"];
            if (strHouseId == null)
            {
                return retExecResult(Constants.ExecResult.Error, "房源标识丢失，请联系管理员！", "");
            }

            Chenxin.Lib.House.Entity.House_BaseInfo clheh = Chenxin.Lib.House.DAL.House_BaseInfo.GetModel(new Guid(strHouseId));

            //要带看的房屋列表
            Dictionary<string, Chenxin.Lib.House.Entity.House_BaseInfo> dicViewHouse;

            //从Cache中获取要带看的房源ID
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
            //Cache要带看房屋的键值
            string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_VIEWHOUSES, CurrentUserInfo.UserId.ToString());
            //从Cache中查找
            dicViewHouse = cs.GetObject(strCacheKey) as Dictionary<string, Chenxin.Lib.House.Entity.House_BaseInfo>;
            //检查Cache是否为空,不为空时其缓存集合中数量是否大于5条
            if (dicViewHouse != null && dicViewHouse.Count >= 5)
            {
                return retExecResult(Constants.ExecResult.Error, "添加失败，超出最大条数！", "");
            }
            else
            {
                //未命中
                if (!cs.Hit)
                {
                    //如果Cache中没有信息,将当前的房源ID添加到Cache中
                    dicViewHouse = new Dictionary<string, Chenxin.Lib.House.Entity.House_BaseInfo>();
                    //当前房源ID添加到列表中
                    dicViewHouse.Add(strHouseId, clheh);
                    //设定Cache中的存活期
                    cs.Set(strCacheKey, dicViewHouse);
                }
                else
                {
                    //检查Cache是否为空
                    if (dicViewHouse == null)
                    {
                        dicViewHouse = new Dictionary<string, Chenxin.Lib.House.Entity.House_BaseInfo>();
                    }
                    //不在Cache列表中的场合
                    if (!dicViewHouse.ContainsKey(strHouseId))
                    {
                        //添加到列表中
                        dicViewHouse.Add(strHouseId, clheh);
                        //重新添加
                        cs.Set(strCacheKey, dicViewHouse);

                    }
                    else
                    {
                        return retExecResult(Constants.ExecResult.Error, "此房源已经添加带看！", ""); 
                    }
                    //删除现有Cache中数据
                    //cs.Delete(strCacheKey);

                }
                //添加用户操作日志 2010-5-13 王玮 Add
                AddLog("" + CurrentUserInfo.UserName + "添加了一个带看:[" + clheh.Community + clheh.BuildingName + clheh.Room + "]已添加房源带看。",
                        OperationType.OperationTypeComboList()["OprType_ViewAdd"].ToString());
                
                return retExecResult(Constants.ExecResult.Succ, "添加成功！", "");

            }
        }
        catch (Exception ex)
        {
            return retExecResult(Constants.ExecResult.Error, ex.Message, "");
        }
    }

    private string DelCacheViewHouse(HttpContext context)
    {
        try
        {

            string strHouseId = context.Request.Params["modelid"];
            if (strHouseId == null)
            {
                return retExecResult(Constants.ExecResult.Error, "房源标识丢失，请联系管理员！", "");
            }
            //房屋实体
            Chenxin.Lib.House.Entity.House_BaseInfo clheh = Chenxin.Lib.House.DAL.House_BaseInfo.GetModel(new Guid(strHouseId));

            //要带看的房屋列表
            Dictionary<string, Chenxin.Lib.House.Entity.House_BaseInfo> dicViewHouse;

            //从Cache中获取要带看的房源ID
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
            //Cache要带看房屋的键值
            string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_VIEWHOUSES, CurrentUserInfo.UserId.ToString());
            //从Cache中查找
            dicViewHouse = cs.GetObject(strCacheKey) as Dictionary<string, Chenxin.Lib.House.Entity.House_BaseInfo>;

            if (cs.Hit)
            {
                //不存在
                if (!dicViewHouse.ContainsKey(strHouseId))
                {
                    return retExecResult(Constants.ExecResult.Error, "要移除的带看房源不存在！", "");
                }
                else
                {
                    //从数据字典中删除
                    dicViewHouse.Remove(strHouseId);
                    //重新添加
                    cs.Set(strCacheKey, dicViewHouse);

                    //添加用户操作日志 2010-5-14 王玮 Add
                    AddLog("" + CurrentUserInfo.UserName + "删除了一个带看:[" + clheh.Community + clheh.BuildingName + clheh.Room + "]已删除房源带看。",
                            OperationType.OperationTypeComboList()["OprType_ViewDel"].ToString());

                    return retExecResult(Constants.ExecResult.Succ, "已将该房源从对带看单中移除！", "");
                }
            }
            else
            {
                return retExecResult(Constants.ExecResult.Error, "要移除的带看房源不存在！", "");
            }

        }
        catch (Exception ex)
        {
            return retExecResult(Constants.ExecResult.Error, ex.Message, "");
        }
    }

    private string DelDbViewHouse(HttpContext context)
    {
        try
        {
            string strRecordId = context.Request.Params["modelid"];

            Chenxin.Lib.House.DAL.Customer_ViewHouseInfo_tmp.Delete(new Guid(strRecordId));

            return retExecResult(Constants.ExecResult.Succ, "已将该房源从对带看单中移除！", "");

        }
        catch (Exception ex)
        {
            return retExecResult(Constants.ExecResult.Error, ex.Message, "");
        }
    }
    
    private string SaveViewHouse(HttpContext context)
    {
        try
        {
            //转换成实体
            Chenxin.Lib.House.Entity.Customer_ViewHouseInfo model = (Chenxin.Lib.House.Entity.Customer_ViewHouseInfo)
                                                                Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.Customer_ViewHouseInfo));
            
            model.AddTime = DateTime.Now;
            model.Operator = CurrentUserInfo.UserName;
            model.OperatorId = CurrentUserInfo.UserId;
            model.OprDepart = CurrentUserInfo.DepartName;
            model.OprDepartId = CurrentUserInfo.DepartId;
            model.CityId = CurrentUserInfo.CityId;
            model.CompanyId = CurrentUserInfo.CompanyId;
            model.ReportCode = "00000-00000-00000-00000";
            model.Status = 0;
            model.RecordId = Guid.NewGuid();
            
            //实例用户实体
            Chenxin.Lib.House.Entity.Customer_BaseInfo modelcbi = new Chenxin.Lib.House.Entity.Customer_BaseInfo();
            //实例带看单房源实体
            Chenxin.Lib.House.Entity.Customer_ViewHouseInfo_tmp modelcvhit = new Chenxin.Lib.House.Entity.Customer_ViewHouseInfo_tmp();

            //设置客源基本信息
            modelcbi.OprPersonId = CurrentUserInfo.UserId;//操作经纪人ID      
            modelcbi.OprPerson = CurrentUserInfo.UserName;//操作经纪        
            modelcbi.OprDepartId = CurrentUserInfo.DepartId;//操作经纪人部门ID  
            modelcbi.OprDepart = CurrentUserInfo.DepartName;//操作经纪人部门
            modelcbi.LastTraceDay = DateTime.Now; //最后跟进日期
            modelcbi.CompanyId = CurrentUserInfo.CompanyId;//门店ID
            modelcbi.CompanyName = CurrentUserInfo.CompanyName;//门店
            modelcbi.CityId = CurrentUserInfo.CityId;//公司ID
            modelcbi.CityName = CurrentUserInfo.CityName;//公司

            modelcbi.Adddate = DateTime.Now;//建档日期
            modelcbi.AddPersonId = CurrentUserInfo.UserId;//所属经纪人ID
            modelcbi.AddPerson = CurrentUserInfo.UserName;//所属经纪人
            modelcbi.AddDepartId = CurrentUserInfo.DepartId;//属经纪人部门ID
            modelcbi.AddDepart = CurrentUserInfo.DepartName;//所属经纪人部门
            modelcbi.OprPersonId = CurrentUserInfo.UserId;//操作经纪人ID
            modelcbi.OprPerson = CurrentUserInfo.UserName;//操作经纪        
            modelcbi.OprDepartId = CurrentUserInfo.DepartId;//操作经纪人部门ID
            modelcbi.OprDepart = CurrentUserInfo.DepartName;//操作经纪人部门
            modelcbi.LastTraceDay = DateTime.Now; //最后跟进日期
            modelcbi.CustomerKind = 30;
            modelcbi.Status = 1;
            modelcbi.PubLevel = 0;
            
            //手动为此实体赋值
            modelcbi.CertificateNo = model.CertificateNo; //身份证号
            modelcbi.Phone = model.Phone;//电话
            modelcbi.Mobile = model.Mobile;//手机
            modelcbi.Address = model.Address;//地址
            modelcbi.Sex = model.Sex;//性别
            modelcbi.CertificateType = model.CertificateType;//证件类型
            modelcbi.Nationality = model.Nationality;//国籍
            modelcbi.CustomerId = Guid.NewGuid();//客户ID
            modelcbi.CustomerName = model.CustomerName;//客户姓名
            modelcbi.CustomerCode = Chenxin.Lib.House.DAL.Customer_BaseInfo.GetCustomerCode(modelcbi.OprPersonId);//客户Code
            
            //要带看的房屋列表
            Dictionary<string, Chenxin.Lib.House.Entity.House_BaseInfo> dicViewHouse;

            //从Cache中获取要带看的房源ID
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
            //Cache要带看房屋的键值
            string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_VIEWHOUSES, CurrentUserInfo.UserId.ToString());
            //从Cache中查找
            dicViewHouse = cs.GetObject(strCacheKey) as Dictionary<string, Chenxin.Lib.House.Entity.House_BaseInfo>;
            
            //检查Cache是否为Null
            if (dicViewHouse != null)
            {
                model.CustomerId = modelcbi.CustomerId;
                //遍历Cache 得到其值(带看房屋的实体集合)
                foreach (KeyValuePair<string, Chenxin.Lib.House.Entity.House_BaseInfo> kvp in dicViewHouse)
                {
                    modelcvhit.RecordId = Guid.NewGuid();
                    modelcvhit.Community = kvp.Value.Community;
                    modelcvhit.BuildingName = kvp.Value.BuildingName;
                    modelcvhit.Room = kvp.Value.Room;
                    modelcvhit.RelationId = model.RecordId;
                    modelcvhit.houseId = kvp.Value.HouseId;
                    modelcvhit.HouseCode = kvp.Value.HouseCode;
                    modelcvhit.CustomerId = kvp.Value.CustomerId;
                    modelcvhit.CustomerName = kvp.Value.CustomerName;
                    modelcvhit.houseAddress = modelcvhit.Community + modelcvhit.BuildingName + modelcvhit.Room;
                    //添加带看单房源
                    Chenxin.Lib.House.BLL.Customer_ViewHouseInfo_tmp.Add(modelcvhit);
                }
                //添加带看单
                Chenxin.Lib.House.DAL.Customer_ViewHouseInfo.Add(model);
                //添加客户
                Chenxin.Lib.House.DAL.Customer_BaseInfo.Add(modelcbi);
                //添加成功后删除带看缓存
                cs.Delete(strCacheKey);
                
                //添加用户操作日志 2010-5-14 王玮 Add
                AddLog("" + CurrentUserInfo.UserName + "添加了带看单:带看客户[" + model.CustomerName + "],带看房源[" + model.houseAddress + "]",
                        OperationType.OperationTypeComboList()["OprType_ViewBringAdd"].ToString());
                
                return retExecResult(Constants.ExecResult.Succ, "生成带看单成功!", "");
            }
            else
            {
                return retExecResult(Constants.ExecResult.Error, "生成带看单失败!", "");
            }
        }
        catch (Exception ex)
        {
            return retExecResult(Constants.ExecResult.Error, ex.Message, "");
        }
    }

    private string EditViewHouse(HttpContext context)
    {
        try
        {
            //转换成实体
            Chenxin.Lib.House.Entity.Customer_ViewHouseInfo model = (Chenxin.Lib.House.Entity.Customer_ViewHouseInfo)
                                                                Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.Customer_ViewHouseInfo));

            model.Operator = CurrentUserInfo.UserName;
            model.OperatorId = CurrentUserInfo.UserId;
            model.OprDepart = CurrentUserInfo.DepartName;
            model.OprDepartId = CurrentUserInfo.DepartId;
            model.CityId = CurrentUserInfo.CityId;
            model.CompanyId = CurrentUserInfo.CompanyId;
            model.Status = 0;

            //实例用户实体
            Chenxin.Lib.House.Entity.Customer_BaseInfo modelcbi = Chenxin.Lib.House.DAL.Customer_BaseInfo.GetModel(model.CustomerId);
            //实例带看单房源实体
            Chenxin.Lib.House.Entity.Customer_ViewHouseInfo_tmp modelcvhit = new Chenxin.Lib.House.Entity.Customer_ViewHouseInfo_tmp();

            //设置客源基本信息
            modelcbi.OprPersonId = CurrentUserInfo.UserId;//操作经纪人ID      
            modelcbi.OprPerson = CurrentUserInfo.UserName;//操作经纪        
            modelcbi.OprDepartId = CurrentUserInfo.DepartId;//操作经纪人部门ID  
            modelcbi.OprDepart = CurrentUserInfo.DepartName;//操作经纪人部门
            modelcbi.LastTraceDay = DateTime.Now; //最后跟进日期
            modelcbi.CompanyId = CurrentUserInfo.CompanyId;//门店ID
            modelcbi.CompanyName = CurrentUserInfo.CompanyName;//门店
            modelcbi.Adddate = DateTime.Now;//建档日期
            modelcbi.AddPersonId = CurrentUserInfo.UserId;//所属经纪人ID
            modelcbi.AddPerson = CurrentUserInfo.UserName;//所属经纪人
            modelcbi.AddDepartId = CurrentUserInfo.DepartId;//属经纪人部门ID
            modelcbi.AddDepart = CurrentUserInfo.DepartName;//所属经纪人部门
         //   modelcbi.OprPersonId = CurrentUserInfo.UserId;//操作经纪人ID
         //   modelcbi.OprPerson = CurrentUserInfo.UserName;//操作经纪        
         //   modelcbi.OprDepartId = CurrentUserInfo.DepartId;//操作经纪人部门ID
         //   modelcbi.OprDepart = CurrentUserInfo.DepartName;//操作经纪人部门
            modelcbi.LastTraceDay = DateTime.Now; //最后跟进日期
            modelcbi.CustomerKind = 30;
            modelcbi.Status = 1;
            //手动为此实体赋值
            modelcbi.CertificateNo = model.CertificateNo; //身份证号
            modelcbi.Phone = model.Phone;//电话
            modelcbi.Mobile = model.Mobile;//手机
            modelcbi.Address = model.Address;//地址
            modelcbi.Sex = model.Sex;//性别
            modelcbi.CertificateType = model.CertificateType;//证件类型
            modelcbi.Nationality = model.Nationality;//国籍
            modelcbi.CustomerId = model.CustomerId;//客户ID
            modelcbi.CustomerName = model.CustomerName;//客户姓名

            //更新带看单
            Chenxin.Lib.House.DAL.Customer_ViewHouseInfo.Update(model);
            //更新客户
            Chenxin.Lib.House.DAL.Customer_BaseInfo.Update(modelcbi);

            return retExecResult(Constants.ExecResult.Succ, "更新带看单成功!", "");
        
        }
        catch (Exception ex)
        {
            return retExecResult(Constants.ExecResult.Error, ex.Message, "");
        }
    }
      
    private string SearchViewHouse(HttpContext context)
    {

        //查询条件
        Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
        Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
        Guid businessdistrict = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
        Guid departs = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
        Guid employee = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);

        //判断权限范围/////////////////////////////////////////////
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        if (employee != Guid.Empty)
            sb.AppendFormat(" AND (ReportorId = '{0}') ", employee);
        else if (departs != Guid.Empty)
            sb.AppendFormat(" AND (DepartId = '{0}')", departs);
        else if (businessdistrict != Guid.Empty)
        {
            Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
            string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, businessdistrict);
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
            if (!cs.Hit)
            {
                item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(businessdistrict);
                if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
            }

            if (item == null)
            {
                return retExecResult(Constants.ExecResult.Error, "获取商圈或分类数据丢失", "");
            }
            sb.Append(" AND (EXISTS(");
            sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
            sb.AppendFormat("WHERE (Customer_ViewHouseInfo.DepartId = M.Departid AND M.DepartSrc like '{0}%'))) ", item.DepartSrc);
        }
        else if (company != Guid.Empty)
        {
            sb.Append(" AND (EXISTS(");
            sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
            sb.AppendFormat("WHERE (Customer_ViewHouseInfo.DepartId = M.Departid AND M.CompanyId='{0}'))) ", company);
        }
        else if (city != Guid.Empty)
        {
            sb.Append(" AND (EXISTS(");
            sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
            sb.AppendFormat("WHERE (Customer_ViewHouseInfo.DepartId = M.Departid AND M.CityId='{0}'))) ", city);
        }

        System.Text.StringBuilder sb1 = new System.Text.StringBuilder();

        //查看所有带看单权限
        if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewHouse_All))
        {
            sb1.Append(" (1=1) ");
        }
        //查看城市带看单权限
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewHouse_City))
        {
            sb1.AppendFormat(" (CityId = '{0}') ", CurrentUserInfo.CityId);
        }
        //查看公司带看单权限
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewHouse_Company))
        {
            sb1.AppendFormat(" (CompanyId = '{0}') ", CurrentUserInfo.CompanyId);
        }
        //查看部门带看单权限
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewHouse_Department))
        {
            sb1.Append(" (EXISTS(");
            sb1.Append("Select 1 from v_Struct_UserDepartRelation M ");
            sb1.AppendFormat("WHERE (Customer_ViewHouseInfo.DepartId = M.Departid AND  M.Userid= '{0}' AND M.ViewWatching = 1 ))) ", CurrentUserInfo.UserId);
        }
        else
        {
            sb1.AppendFormat(" (ReportorId = '{0}')", CurrentUserInfo.UserId);
        }

        if (!String.IsNullOrEmpty(sb.ToString()))
            sb1.Append(sb.ToString());

        //开始带看时间
        if (!string.IsNullOrEmpty(context.Request.Params["txtsearchstartime"]))
        {
            sb1.AppendFormat("and convert(varchar(10),(convert(datetime,ViewTime,120)),120) >= '{0}'", context.Request.Params["txtsearchstartime"]);
        }
        //结束带看时间
        if (!string.IsNullOrEmpty(context.Request.Params["txtsearchendtime"]))
        {
            sb1.AppendFormat("and convert(varchar(10),(convert(datetime,ViewTime,120)),120) <= '{0}'", context.Request.Params["txtsearchendtime"]);
        }

        if (!string.IsNullOrEmpty(context.Request.Params["txtcustomername"]))
        {
            sb1.AppendFormat("and (EXISTS(Select 1 from Customer_BaseInfo M WHERE (Customer_ViewHouseInfo.CustomerId = M.CustomerId and M.CustomerName LIKE '{0}%')))", context.Request.Params["txtcustomername"]);
        }
        if (!string.IsNullOrEmpty(context.Request.Params["txtcustomerphone"]))
        {
            sb1.AppendFormat(" and (EXISTS(Select 1 from Customer_BaseInfo M WHERE (Customer_ViewHouseInfo.CustomerId = M.CustomerId and (M.Mobile LIKE '%{0}%' OR M.Phone Like '%{0}%' ))))",context.Request.Params["txtcustomerphone"]);
        }
        
        //根据查询条件生成一个Table
        return GetViewHouse(context, sb1.ToString());

    }

    public string GetViewHouse(HttpContext context, string strWhere)
    {
        try
        {
            int count = 0;
            Constants.Pagination stuPg = new Constants.Pagination();

            //页码
            int strPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            //页显示行数
            int strPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
            //排序
            string strOrderField = "AddTime desc";

            //欲选择字段列表 
            string FieldList = "RecordId,CustomerName,CustomerId,Reportor,ReportDepart,Operator,OprDepart,AddTime,ViewTime,houseId,houseAddress";
            //子查询欲选择字段列表
            string TableFieldList = "RecordId,CustomerName,CustomerId,Reportor,ReportDepart,Operator,OprDepart,AddTime,ViewTime,houseId,houseAddress";

            //所要查询的表名
            string TableName = "Customer_ViewHouseInfo";
            //根据sql执行查询
            DataSet ds = Chenxin.Lib.House.DAL.Customer_ViewHouseInfo.GetList(strPageIndex, strPageSize, strOrderField, TableName, strWhere, FieldList, TableFieldList, true);
            //数据行数
            count = (int)ds.Tables[1].Rows[0][0];

            string strHtml = string.Empty;

            if (!GetViewHouseHtml(ds, out strHtml))
            {
                return retExecResult(Constants.ExecResult.Error, "生成HTML错误", "");
            }
            stuPg.count = count;
            stuPg.data = strHtml.ToString();

            return retExecResult(Constants.ExecResult.Succ, "OK", stuPg);

        }
        catch (Exception ex)
        {
            return retExecResult(Constants.ExecResult.Error, ex.Message, "");
        }
    }

    private bool GetViewHouseHtml(DataSet dslist, out string strHtml)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<table width=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
        sb.Append("<thead>");
        sb.Append("<tr><th width=\"18%\">操作</th>");
        sb.Append("<th width=\"10%\">带看客户</th>");
        sb.Append("<th width=\"20%\">带看人</th>");
        sb.Append("<th width=\"12%\">带看人部门</th>");
        sb.Append("<th width=\"12%\">添加人</th>");
        sb.Append("<th width=\"12%\">添加人部门</th>");
        sb.Append("<th width=\"15%\">带看时间</th>");
        sb.Append("</tr>");
        sb.Append("</thead>");
        sb.Append("<tbody>");
        
        foreach (DataRow row in dslist.Tables[0].Rows)
        {
            sb.AppendFormat("<tr id=\"{0}\">", row["RecordId"].ToString());
            sb.AppendFormat("<td>");
            sb.AppendFormat("<a name=\"{0}\" id=\"btn_viewhouseinfo\" href=\"javascript:void(0)\">详情</a> | <a name=\"{0}\" id=\"btn_viewhouseedit\" href=\"javascript:void(0)\">编辑</a>", row["RecordId"].ToString());
            sb.AppendFormat(" | <a name=\"{0}\" id=\"btn_trace\" href=\"javascript:void(0)\">跟单</a> | <a name=\"{0}\" id=\"btn_viewtrace\" href=\"javascript:void(0)\">查跟单</a>", row["CustomerId"].ToString());
            sb.AppendFormat("</td>");
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "CustomerName", ""));
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Reportor", ""));
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ReportDepart", ""));
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Operator", ""));
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OprDepart", ""));
            sb.AppendFormat("<td>{0:yyyy-mm-dd }</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ViewTime", ""));
            sb.Append("</tr>");
            sb.Append("<tr>");
            sb.Append("<td colspan=\"7\">");
            //获取带看单房源
            DataSet ds = Chenxin.Lib.House.DAL.Customer_ViewHouseInfo_tmp.GetList(string.Format(" RelationId = '{0}'", new Guid(row["RecordId"].ToString())));
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                sb.AppendFormat("<span>[<a href=\"ShowDetailInfo.aspx?houseid={0}\" target=\"blank\">{1}</a>] </span>",
                                    dr["houseId"].ToString(),
                                    dr["houseAddress"].ToString());
            }    

            sb.Append("</td></tr>");
        }

        sb.Append("</tbody></table>");

        strHtml = sb.ToString();
        return true;
    }

    private string GetCacheViewHouseList(HttpContext context)
    {
        DataSet ds = null;
        //要带看的房屋列表
        Dictionary<string, Chenxin.Lib.House.Entity.House_BaseInfo> dicViewHouse = null;
        string strstyle = string.Empty;
        
        if (!string.IsNullOrEmpty(context.Request["RecordId"]))
        {
            ds = Chenxin.Lib.House.DAL.Customer_ViewHouseInfo_tmp.GetList(string.Format(" RelationId = '{0}'", new Guid(context.Request["RecordId"].ToString())));
            if (ds != null && ds.Tables[0].Rows.Count > 3)
            {
                strstyle = "height:110px; overflow-y:auto;";   
            }
        }
        else
        {

            //从Cache中获取要带看的房源ID
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
            //Cache要带看房屋的键值
            string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_VIEWHOUSES, CurrentUserInfo.UserId.ToString());
            //从Cache中查找
            dicViewHouse = cs.GetObject(strCacheKey) as Dictionary<string, Chenxin.Lib.House.Entity.House_BaseInfo>;
            if (dicViewHouse != null && dicViewHouse.Count > 3)
            {
                strstyle = "height:110px; overflow-y:auto;";
            }
        }
        
        Constants.Pagination stuPg = new Constants.Pagination();
        StringBuilder sb = new StringBuilder();
        sb.Append("<div style=\"" + strstyle + "\">");
        sb.Append("<table width=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
        sb.Append("<thead>");
        sb.Append("<tr>");
        sb.Append("<th width=\"35%\" style=\"text-align:left;\">房源编号</th>");
        sb.Append("<th width=\"35%\" style=\"text-align:left;\">楼盘/门号/房号</th>");
        if (string.IsNullOrEmpty(context.Request["RecordId"])) sb.Append("<th width=\"20%\" style=\"text-align:left;\">部门</th>");//
        if (string.IsNullOrEmpty(context.Request["RecordId"])) sb.Append("<th width=\"10%\" style=\"text-align:left;\">操作</th>");
        sb.Append("</tr>");
        sb.Append("</thead>");
        sb.Append("<tbody>");

        if (!string.IsNullOrEmpty(context.Request["RecordId"]))
        {
            if (ds != null && ds.Tables[0].Rows.Count != 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    sb.AppendFormat("<tr id=\"{0}\">", dr["RecordId"].ToString());
                    sb.AppendFormat("<td>{0}</td>", dr["HouseCode"].ToString());
                    sb.AppendFormat("<td>{0} {1} {2}</td>", dr["Community"].ToString(), dr["BuildingName"].ToString(), dr["Room"].ToString());
                   // if (string.IsNullOrEmpty(context.Request["type"])) sb.AppendFormat("<td><a name=\"{0}\" id=\"btn_deldbview\" href=\"#\">移除</a>", dr["RecordId"].ToString());
                    sb.Append("</tr>");
                }
                stuPg.count = ds.Tables[0].Rows.Count;
            }
            else
            {
                sb.Append("<tr><td colspan=\"4\" style=\"text-align:center;\" >带看房源不存在，请添加带看房源后再生成带看单！</td></tr>");
            }
        }
        else
        {

            if (dicViewHouse != null && dicViewHouse.Count != 0)
            {
                foreach (KeyValuePair<string, Chenxin.Lib.House.Entity.House_BaseInfo> kvp in dicViewHouse)
                {
                    sb.AppendFormat("<tr id=\"{0}\">", kvp.Value.HouseId.ToString());
                    sb.AppendFormat("<td>{0}</td>", kvp.Value.HouseCode);
                    sb.AppendFormat("<td>{0} {1} {2}</td>", kvp.Value.Community, kvp.Value.BuildingName, kvp.Value.Room);
                    sb.AppendFormat("<td>{0}</td>", kvp.Value.OprDepart);
                    sb.AppendFormat("<td><a name=\"{0}\" id=\"btn_delcacheview\" href=\"javascript:void(0)\">移除</a>", kvp.Value.HouseId.ToString());
                    sb.Append("</tr>");
                }
                stuPg.count = dicViewHouse.Count;
            }
            else
            {
                sb.Append("<tr><td colspan=\"4\" style=\"text-align:center;\" >带看房源不存在，请添加带看房源后再生成带看单！</td></tr>");
            }
        }
        sb.Append("</tbody></table>");
        sb.Append("</div>");
        stuPg.data = sb.ToString();
        
        return retExecResult(Constants.ExecResult.Succ, "OK", stuPg);
    }

    private string GetViewHouseModel(HttpContext context)
    {
        Guid modelId = (string.IsNullOrEmpty(context.Request["modelid"])) ? Guid.Empty : new Guid(context.Request["modelid"]);

        if (modelId == Guid.Empty)
        {
            return retExecResult(Constants.ExecResult.Error, "带看单丢失，请联系管理员！", "");
        }

        Chenxin.Lib.House.Entity.Customer_ViewHouseInfo model = Chenxin.Lib.House.DAL.Customer_ViewHouseInfo.GetModel(modelId);
        if (model == null)
        {
            return retExecResult(Constants.ExecResult.Error, "带看单不存在，请联系管理员！", "");
        }
        Chenxin.Lib.House.Entity.Customer_BaseInfo modelcbi = Chenxin.Lib.House.DAL.Customer_BaseInfo.GetModel(model.CustomerId);
        if (modelcbi == null)
        {
            return retExecResult(Constants.ExecResult.Error, "客户信息丢失，请联系管理员！", "");
        }
        model.CertificateNo = modelcbi.CertificateNo; //身份证号
        model.Phone = modelcbi.Phone;//电话
        model.Mobile = modelcbi.Mobile;//手机
        model.Address = modelcbi.Address;//地址
        model.Sex = modelcbi.Sex;//性别
        model.CertificateType = modelcbi.CertificateType;//证件类型
        model.Nationality = modelcbi.Nationality;//国籍
        model.CustomerId = modelcbi.CustomerId;//客户ID
        model.CustomerName = modelcbi.CustomerName;//客户姓名
        
        //return retExecResult(Constants.ExecResult.Succ, "成功", model);
        return string.Format("{{success:'1',msg:'成功',data:{{model:{0}}}}}",
                Chenxin.Lib.Utility.JsonHelp.Convert2Json(model));
    }


    //*******************************************
    //功能概要       ：响应字符串
    //参数説明       ：strMsg 消息 
    //返回值説明     ：void
    //功能詳細       ：权限检查
    //作成者         ：chen.yugong 
    //作成日         ：2010-05-20
    //修改者         ：
    //修改日         ：
    //*******************************************
    public override bool CustomerCheckPermint(HttpContext context, out string strMsg)
    {
        if (context.Request["op"] != null)
        {
            string op = context.Request["op"].ToLower();
            //传递参数用
            System.Collections.Hashtable per = new System.Collections.Hashtable();
            System.Collections.Hashtable confine = new System.Collections.Hashtable();
            //如果是保护和取消保护
            if (op.Equals("checkpermit") && "edit".Equals(context.Request["code"].ToLower()))
            {
                Chenxin.Lib.House.Entity.Customer_ViewHouseInfo model = null;
                try
                {
                    string id = context.Request["currentId"];
                    if (string.IsNullOrEmpty(id))
                    {
                        strMsg = "{success:0,msg:'带看主键为空，获取数据失败！',data:''}";
                        return false;
                    }
                    model = Chenxin.Lib.House.DAL.Customer_ViewHouseInfo.GetModel(new Guid(id));
                    if (model == null)
                    {
                        strMsg = "{success:0,msg:'带看数据不存在，获取数据失败！',data:''}";
                        return false;
                    }
                    //加入权限项
                    per.Add("ALL", Constants.Permit_EditHouseView_All);
                    per.Add("CITY", Constants.Permit_EditViewHouse_City);
                    per.Add("COMPANY", Constants.Permit_EditViewHouse_Company);
                    per.Add("DEPART", Constants.Permit_EditViewHouse_Department);
                    //加入范围
                    confine.Add("CityId", model.CityId);
                    confine.Add("CompanyId", model.CompanyId);
                    confine.Add("OperatorId", model.OperatorId);
                    //检查权限
                    return CheckPermint(per, confine, checkDepartPermit(model.OprDepartId, context.Request["code"].ToLower()), out strMsg);

                }
                catch (Exception ex)
                {
                    strMsg = "{success:0,msg:'" + ex.Message + "',data:''}";
                    return false;
                }

            }
        }
        strMsg = "{success:1,msg:'',data:{permit:true}}";
        return true;
    }

    public bool checkDepartPermit(Guid departId, string op)
    {
        //检查有无权限
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.AppendFormat(" (Departid = '{0}' AND  Userid= '{1}') ", departId, CurrentUserInfo.UserId);
        System.Collections.Generic.List<Chenxin.Lib.Hr.Entity.Struct_UserDepartRelation> list = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.GetListArray(sb.ToString());
        if (list!=null && list.Count > 0)
        {
            Chenxin.Lib.Hr.Entity.Struct_UserDepartRelation hrp = list[0];
            //修改带看
            if ("edit".Equals(op))
            {
                return hrp.EditWatching;
            }
        }
        return false;
    }

    //通过客户ID查找带看单ID
    private string GetViewHouseId(HttpContext context)
    {
        string strRet = string.Empty;
        string CustomerId = context.Request.Params["CustomerId"];

        DataSet dsId = Chenxin.Lib.House.BLL.Customer_ViewHouseInfo.GetModelId(CustomerId);

        if (dsId.Tables[0].Rows.Count > 0)
        {
            strRet = retExecResult(Constants.ExecResult.Succ, "", dsId.Tables[0].Rows[0]["RecordId"].ToString());
        }
        else
        {
            strRet = retExecResult(Constants.ExecResult.Error, "参数有误", "");
        }
        return strRet;
    }    
}
